package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.pojo.Order;
import com.jt.service.DubboCartService;
import com.jt.service.DubboOrderService;
import com.jt.thread.UserThreadLocal;
import com.jt.vo.SysResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Reference(check = false, timeout = 3000)
    private DubboCartService cartService;

    @Reference(check = false, timeout = 3000)
    private DubboOrderService orderService;

    /**
     * 订单确认页面的跳转
     * url
     */
    @RequestMapping("/create")
    public String findCartByUserId(Model model) {
        Long userId = UserThreadLocal.get().getId();
        List<Cart> cartList = cartService.findCartListByUserId(userId);
        model.addAttribute("carts", cartList);
        return "order-cart";
    }

    /**
     * 完成订单业务提交
     * url : /order/submit
     * 参数 整个form对象
     * 返回值 : SysResult对象(orderId);
     *
     * @return
     */
    @RequestMapping("/submit")
    @ResponseBody
    public SysResult submit(Order order) {

        Long userId = UserThreadLocal.get().getId();
        order.setUserId(userId);
        String orderId = orderService.saveOrder(order);
        if (StringUtils.isEmpty(orderId)) {
            return SysResult.fail();
        }
        return SysResult.success(orderId);
    }

    /**
     * 订单查询
     * /order/success
     */
    @RequestMapping("/success")
    public String findOrderById(String id, Model model) {
        Order order = orderService.findOrderById(id);
        model.addAttribute("order", order);
        return "success";
    }
}
